(function($, win, doc, undefined){

	var aesPwd = 'Xxeicq3gknHJEsZR';
	var app = null;

	/**
	 *  默认值：/seeyon
	 */
	var appBasePath = (function(){
		
		var path = location.pathname;
		
		return path.substring(0, path.indexOf('/', 1));
	})();
	
	function getDialog(){
		
		return  win.parentDialogObj && win.parentDialogObj["ctrlDialog"];
	}
	
	function getTransParams(){
				
		return getDialog().getTransParams();
	}
	
	var htmlMirror = (function (){
		
		var editor = null;
		var script = null;

		return {
			init: function(fnName){
				
				setTimeout(function(){
					
					if(null != editor){
						
						$.setCSS(editor.getWrapperElement(), {display: 'block'});
						
						return;
					}
					
					if($.isBlank(script)){
						
						var btnId = 'dlinkBtn_'  + Snail.dateFormat(new Date(), 'yyyyMMddHHmmss');
						
						$.setEleValue('#script_content', (function(){
							
							var scriptTxt = [''];
							scriptTxt.push('<template>');
							scriptTxt.push('    <div id="' + btnId + '">Visit W3School</div>');
							scriptTxt.push('</template>');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('');
							scriptTxt.push('<style type="text/css">');
							scriptTxt.push('#' + btnId + ' {');
							scriptTxt.push('    color: #DA0000; width: auto; min-width: 120px; height: 30px; line-height: 28px; ');
							scriptTxt.push('    padding: 0px 15px; margin: 2px auto;');
							scriptTxt.push('    border: 1px solid rgb(212, 212, 212); border-radius: 15px; background-color: #ffffff;');
							scriptTxt.push('    display: inline-block; white-space: nowrap; text-align: center;');
							scriptTxt.push('    cursor: pointer; ');
							scriptTxt.push('}');
							scriptTxt.push('#' + btnId + ':focus, #' + btnId + ':hover {');
							scriptTxt.push('    font-weight: 600; ');
							scriptTxt.push('}');
							scriptTxt.push('</style>');
							scriptTxt.push('');
							scriptTxt.push('<script type="text/javascript">');
							scriptTxt.push('/** ');
							scriptTxt.push(' * 【' + fnName +'】 DLink 控件');
							scriptTxt.push(' */ ');
							scriptTxt.push('(function ($, factory) {');
							scriptTxt.push('    ');
							scriptTxt.push('    /** ');
							scriptTxt.push('     * 空间名，由【DLINK_2022_ + 控件名】组成，不可随意修改');
							scriptTxt.push('     * ');
							scriptTxt.push('     * ※※※※※※※※ 控件名修改后，必须对空间名进同步修改 ※※※※※※※※');
							scriptTxt.push('     */ ');
							scriptTxt.push('    var nameSpace = \'DLINK_2022_' + fnName +'\';');
							scriptTxt.push('    ');
							scriptTxt.push('    if(!window[nameSpace]){');
							scriptTxt.push('        ');
							scriptTxt.push('        var Builder = factory($, nameSpace, window, document);');
							scriptTxt.push('        ');
							scriptTxt.push('        var plugin = window[nameSpace] = {');
							scriptTxt.push('            instance: {}');
							scriptTxt.push('        };');
							scriptTxt.push('        ');
							scriptTxt.push('        plugin.init = function (options) {');
							scriptTxt.push('            window[nameSpace].instance[options.privateId] = new Builder(options);');
							scriptTxt.push('        };');
							scriptTxt.push('    }else{');
							scriptTxt.push('        console.log(\'【提示】检测到空间名可能重复了，请确认！如果您已确认不影响运行，请忽略此提示。\', nameSpace);');
							scriptTxt.push('    }');
							scriptTxt.push('})(Snail, function($, domain, _win, _doc, undefined){');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    function DLinkApp(options) {');
							scriptTxt.push('        ');
							scriptTxt.push('        this.options = options;');
							scriptTxt.push('        this.el = options.el;');
							scriptTxt.push('        this.data = options.getData;');
							scriptTxt.push('        this.field = options.field;');
							scriptTxt.push('        this.privateId = options.privateId;');
							scriptTxt.push('        ');
							scriptTxt.push('        this.init(options);');
							scriptTxt.push('    }');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    DLinkApp.prototype.init = function(options) {');
							scriptTxt.push('        ');
							scriptTxt.push('        console.log(options);');
							scriptTxt.push('        ');
							scriptTxt.push('        $.bindEvent("#' + btnId + '", "click", function(ev){');
							scriptTxt.push('            ');
							scriptTxt.push('            console.log($.dlink);');
							scriptTxt.push('            ');
							scriptTxt.push('            /** ');
							scriptTxt.push('             * 获取服务器端数据（缓存，注：可能存在部分前端数据未提交到');
							scriptTxt.push('             * 缓存，造成数据为 null 的现象！可以从 this.data 中获取）');
							scriptTxt.push('             */ ');
							scriptTxt.push('            var data = $.dlink.getData();');
							scriptTxt.push('            console.log(data);');
							scriptTxt.push('            ');
							scriptTxt.push('            ');
							scriptTxt.push('            window.open("https://www.w3school.com.cn?ticket=" + $.dlink.getTicket(), "_blank");');
							scriptTxt.push('        ');
							scriptTxt.push('        });');
							scriptTxt.push('    };');
							scriptTxt.push('    ');
							scriptTxt.push('    ');
							scriptTxt.push('    return DLinkApp;');
							scriptTxt.push('});');
							scriptTxt.push('</script>');
							scriptTxt.push('');
							scriptTxt.push('');
							
							return scriptTxt.join('\r\n');
						})());
						
					}else{
						$.setEleValue('#script_content', script);
					}
					
					editor = CodeMirror.fromTextArea($.getElement('#script_content'), {
						mode: {
					        name: "htmlmixed",
					        scriptTypes: [
					        	{matches: /\/x-handlebars-template|\/x-mustache/i, mode: null},
					            {matches: /(text|application)\/(x-)?vb(a|script)/i, mode: "vbscript"}
					        ],
					        tags: {
					            style: [
					            	["type", /^text\/(x-)?scss$/, "text/x-scss"],
					                [null, null, "css"]
					            ],
					            custom: [
					            	[null, null, "customMode"]
					            ]
					        }
					    },
						theme: "darcula",
						selectionPointer: true,
						lineNumbers: true,
						lineWrapping: true,
						indentUnit: 4,
						extraKeys: {
							'Ctrl': 'autocomplete'
						},
						hintOptions: {
							completeSingle: false
						}
					});
					
					editor.on('keypress', function(){
						//编译器内容更改事件
						editor.showHint();
					});
					
					editor.refresh();
					
				}, 200);
			},
			setValue: function(_script){
				
				script = $.aes_decrypt((_script ? decodeURIComponent(_script) : ''), aesPwd);
				
				if(null == editor){
					return ;
				}
				
				editor.setValue(script);
			},
			getValue: function(){
				return $.aes_encrypt((editor ? editor.getValue() : script), aesPwd);
			},
			getPlaintext: function(){
				return (editor ? editor.getValue() : script);
			},
			close: function(){
				editor && $.setCSS(editor.getWrapperElement(), {display: 'none'});
			}
		}
	})();
	
	
	
	
	/**
	 * 初始化窗口
	 */
	function initWindow(){
		
		var dialog = $.getElement('div[laytype="dialog"]', 0, window.parent.document);
				
		var width = window.screen.width || window.screen.availWidth;
		
		if(1440 < width){
			
			$.setCSS(dialog, {
				width: 'calc(100% - 100px)', height: 'calc(100% - 70px)',
				top: '35px', left: '50px'
			});
			
		}else{
			
			$.setCSS(dialog, {
				width: 'calc(100% - 50px)', height: 'calc(100% - 20px)',
				top: '10px', left: '25px'
			});
		}

		var dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: 'calc(100% - 105px)'
		});
		
		dialogWindow = $.getElement('div[laytype="dialog"]>div:nth-child(2)>iframe', 0, window.parent.document);
		
		$.setCSS(dialogWindow, {
			height: '100%'
		});
		
		var dialogTitle = $.getElement('div[laytype="dialog"]>div:first-child', 0, window.parent.document);
		
		$.cleanHtml(dialogTitle);
		$.appendHtml(dialogTitle, 'DLink 配置器');
	}
	
	/**
	 * 初始化Mirror
	 */
	function initMirror(){

		var transParams = getTransParams();
		var fnName = transParams.currentfield.display;
		
		htmlMirror.init(fnName);

		htmlTxt = (transParams ? (transParams.params ? transParams.params : '') : '');
		
		htmlMirror.setValue(htmlTxt);
	}
	
	
	$.extend('app',{
		
		init: function(){
			
			initWindow();
			
			initMirror();
		}
	});

	/**
	 *	保存返回数据
	 */
	win['OK'] = function() {
						
		return {
			valid: true, 
			data: htmlMirror.getValue()
		};
	}
	
})(Snail, window, document);